<template>
  <div :key="forceKey" style="display:flex;height: 100%;overflow-x: auto">


    <div style="flex-shrink: 0;height: 100%;display: flex">
    <file-view-search-file   :file-tree="$store.state.fileViewSearch.fileTree"
                             ref="fileViewRef"          :keyword="searchKey"

                             @view="viewFile"
                             @download="dowloadFile"
                             @share="getShareUrl"
                             @shouchang="shouchangFile"
    ></file-view-search-file>
    </div>
    <el-dialog
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :before-close="()=>showReviewer=false"
        :visible.sync="showReviewer"
        title="预览"
        width="90%"
    >
      <div v-if="viewShowNode&&viewShowNode.href" v-loading="viewLoading" class="viewbox">
        <div  v-if="viewShowNode.type=='pptx'" style="width: 100%;height: 100%;text-align: center;background: rgba(0,0,0,0.3)">
          <div  id="pptxview" style="max-height: 100%;max-width: 100%" />
        </div>
        <div  v-if="viewShowNode.type=='image'" style="width: 100%;height: 100%;text-align: center;background: rgba(0,0,0,0.3)">
          <img  :src="viewShowNode.href" style="max-height: 100%;max-width: 100%">
        </div>
        <vue-office-pdf v-if="viewShowNode.type=='pdf'" :options="{lazy:true}" :src="viewShowNode.href" style="flex: 1;" @rendered="rendered" />

        <div  v-if="viewShowNode.type=='word'" style="width: 100%;height: 100%;text-align: center">
          <vue-office-docx  :src="viewShowNode.href" style="flex: 1;" @rendered="rendered" />
        </div>
        <div  v-if="viewShowNode.type=='excel'" style="width: 100%;height: 100%;text-align: center">

          <vue-office-excel  :src="viewShowNode.href"   @rendered="rendered" />
        </div>
        <iframe v-if="viewShowNode.type=='txt'||viewShowNode.type=='text'" :src="viewShowNode.href" style="width: 100%;height: 100%;border: none" />

        <div  v-if="viewShowNode.type=='EPM'" style="width: 100%;height: 100%;text-align: center">
          <div  v-html="viewShowNode.href" >

          </div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showReviewer = false">取 消</el-button>
        <el-button type="primary" @click="showReviewer = false">确 定</el-button>
<!--        <el-button type="danger" @click="printFile">打 印</el-button>-->
      </span>
    </el-dialog>
    <el-dialog
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :before-close="()=>showShare=false"
        :visible.sync="showShare"
        title="文件文享"
        width="700px"
    >
      <div style="display: flex;align-items: center">
        <div style="width: 80px;text-align: right;margin-right: 10px">文件地址:</div>
        <el-input v-model="shareurl" :readonly="true" />
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showShare = false">关 闭</el-button>
        <el-button class="copy-btn" :data-clipboard-text="shareurl" type="primary" @click="copyshareUrl">复制地址</el-button>
      </span>
    </el-dialog>
    <spare-view ref="sparedetail"/>
    <parts-change-view ref = "partsview" />
     <relocation-view ref="srelocationView" />
    <mis-detail ref="misDetail"/>
  </div>
 </template>
<script>
import splitPane from 'vue-splitpane'
import waves from '@/directive/waves'
import Template from '@/views/bs/template.vue'
import FileView from "@/views/Knowledge/fileViewSearch.vue";
import {downBlobFile, fetchTree, getEmpData, getShareUrl, shoucang, viewBlobFile, getSpmData} from "@/api/common";
import uuid from "uuid"
import {queryFileTree} from "@/api/technology";
import FileViewSearchFile from "@/views/Knowledge/fileViewSearchFile.vue";
import _ from "lodash";
import VueOfficePdf from "@vue-office/pdf";
import VueOfficeDocx from "@vue-office/docx";
import {fetchList} from "@/api/article";
import VueDraggableResizable from 'vue-draggable-resizable'
import 'vue-draggable-resizable/dist/VueDraggableResizable.css'
import {getToken} from "@/utils/auth";
import {Base64} from "js-base64";
import SpareDetail from "@/views/bs/spareDetail.vue";
import SpareView from "@/views/bs/spareView.vue";
import RelocationView from "@/views/bs/relocationView.vue";
import PartsChangeView from "@/views/bs/partsChangeView.vue";
import MisDetail from "@/views/bs/misDetail.vue";

export default {
  name: 'publicSearch',
  components: {
    MisDetail,
    PartsChangeView, RelocationView,
    SpareView,
    VueOfficeDocx, VueOfficePdf, FileViewSearchFile, FileView, Template, splitPane,VueDraggableResizable },
  directives: { waves },
  props: {
    fileTree: {
      type: Object,
      default: () => {
        return {}
      }
    },
    keyword:"",
  },
  data: function() {
    return {
      lineTreeWidth:280,
      stationWidth:200,
      treedata: [],
      defaultProps: {
        children: 'children',
        label: 'department_name'
      },
      station_id:'',
      treeloading: false,
      treeExpand: [],      width:200,
      showShare: false,
      shareurl: '',
      viewLoading: false,
      viewShowNode: null,
      showReviewer: false,
      searchKey: '',
      listLoading:false,
      forceKey: 0,
      gutters: [5, 5, 5, 33, 50],
    }
  },
  beforeDestroy(){
    this.$store.state.fileViewSearch.fileTree.selectKey="";
    this.$store.state.fileViewSearch.fileTree={};
    this.$store.state.fileViewSearch.stationList=[];
    this.station_id=""
    console.log("调用了组件")
  },
  mounted() {
    this.getList()
  },
  methods: {
    printFile() {

    },
    copyshareUrl() {
      var element = this.createElement(this.shareurl)
      element.select()
      element.setSelectionRange(0, element.value.length)
      document.execCommand('copy')
      element.remove()
      this.$message.success('已复制到剪贴板！')
    },
    getShareUrl(node) {
      this.loading = true
      const data = {
        file_id: node.id,
        inc_type: node.inc_type == 'dir' ? 'dir' : 'file',
        station_id: this.station_id
      }
      getShareUrl(data).then((res) => {
        this.loading = false
        console.log('分享', res)
        this.shareurl = res.data
        this.showShare = true
      }).catch(() => {
        this.loading = false
      })
    },
    shouchangFile(node) {
      shoucang({ file_id: node.id, station_id: this.station_id, path: JSON.stringify(this.$store.state.fileViewSearch.fileTree) }).then((res) => {
        // 刷新收藏
        this.geShoucang()
        this.$message.success(res.msg)
      })
    },
    geShoucang() {
      console.log('用户信息', this.$store.state.user)

      const listQuery = {
        page_no: 1,
        limit: 100,
        sort: 'id desc',
        where: { and: [{ field: 'user_id', operator: '=', value: this.$store.state.user.user_id }] }
      }
      fetchList(listQuery, 'sl_view_collect').then(response => {
        console.log('回复', response)
        if (response.data) {
          this.$store.state.fileViewSearch.myCollection = response.data.items
        }
      }).catch((e) => {
        this.treeloading = false
      })
    },
    rendered() {
      console.log('预览加载完成')
      this.viewLoading = false
    },
    dowloadFile(node) {
      downBlobFile({ file_id: node.id }, node.name)
    },
    viewFile(node) {
      console.log('想看权限',node)
      if(node.promise&&node.promise.is_read===0)
      {
        this.$message.error('您没有查看此文件的权限')
        return
      }
      var has = this.$store.state.fileViewSearch.recentViews.filter(item => item.id == node.id)
      if (!has || has.length == 0) {
        if ((this.$store.state.fileViewSearch.recentViews.length+this.$store.state.fileViewSearch.recentViewsFixed.length) >= 10) {
          this.$store.state.fileViewSearch.recentViews = this.$store.state.fileViewSearch.recentViews.splice(this.$store.state.fileViewSearch.recentViews.length-1)
        }
        this.$store.state.fileViewSearch.recentViews.unshift({ id: node.id, name: node.name, path: _.cloneDeep(this.$store.state.fileViewSearch.fileTree) })
        localStorage.setItem("fileViewCache",JSON.stringify(this.$store.state.fileViewSearch.recentViews))
        localStorage.setItem("fileViewCacheFixed",JSON.stringify(this.$store.state.fileViewSearch.recentViewsFixed))
      }
      this.viewShowNode = { type: node.inc_type, href: '' }
      if(node.inc_type=='EPM'){
        getEmpData(this.$store.state.fileViewSearch.station_id).then((res)=>{
          this.viewShowNode = { type: node.inc_type, href: res.data }
          console.log("展示EPM",this.viewShowNode)

          this.showReviewer = true
          this.viewLoading = false

        })
      }else if(node.inc_type=='SPM')
      {
        var inc_type='spm';
        getSpmData(inc_type).then((res)=>{
          if(res.data){
            window.open(res.data);
          }
        })
      }else if(node.inc_type=='MIS+')
      {

       inc_type='mis'
        getSpmData(inc_type).then((res)=>{
          if(res.data){
            this.$refs.misDetail.show(res.data)
          }
        })
      }else if(node.inc_type=='cad')
      {

        var element = this.createElement(node.name)
        element.select()
        element.setSelectionRange(0, element.value.length)
        document.execCommand('copy')
        element.remove()
        if(node.path){
          window.open(node.path);
        }

      }else if(node.inc_type=='Process Key parts')
      {
        this.$refs.sparedetail.show(this.$store.state.fileViewSearch.station_id);

      }else if(node.inc_type=='reuse/relocation record')
      {
        this.$refs.srelocationView.show(this.$store.state.fileViewSearch.station_id);
      }else if(node.inc_type=='process/parts change list')
      {
        this.$refs.partsview.show(this.$store.state.fileViewSearch.station_id);
      }else{
        //组装加密url
        var token =getToken();
        var previewUrl=process.env.VUE_APP_BASE_URL+'/api/devfile/down?file_id='+node.id+"&Accesstoken="+token+"&fullfilename="+node.name;

        console.log('previewUrl',previewUrl)

        window.open("http://cngvm00100.apac.bosch.com:8012/onlinePreview?url="+encodeURIComponent(Base64.encode(previewUrl)));

      }

    },
    createElement(text) {
      var isRTL = document.documentElement.getAttribute('dir') === 'rtl'
      var element = document.createElement('textarea')
      // 防止在ios中产生缩放效果
      element.style.fontSize = '12pt'
      // 重置盒模型
      element.style.border = '0'
      element.style.padding = '0'
      element.style.margin = '0'
      // 将元素移到屏幕外
      element.style.position = 'absolute'
      element.style[isRTL ? 'right' : 'left'] = '-9999px'
      // 移动元素到页面底部
      const yPosition = window.pageYOffset || document.documentElement.scrollTop
      element.style.top = `${yPosition}px`
      // 设置元素只读
      element.setAttribute('readonly', '')
      element.value = text
      document.body.appendChild(element)
      return element
    },
    getList() {
      this.treeloading = true
      fetchTree(this.listQuery, '/api/auth/getdeptlist').then(response => {
        if (response.data) {
          this.treedata = response.data
          this.treeExpand = response.data.map((item) => {
            return item.id
          })
        }
        this.treeloading = false
      }).catch((e) => {
        this.treeloading = false
      })
    },
    selectStation(key) {
      this.$store.state.fileViewSearch.stationList.forEach(async (item, i) => {
        if (key !== i) {
          this.$store.state.fileViewSearch.stationList[i]['selected'] = false
        } else {
          this.$store.state.fileViewSearch.stationList[i]['selected'] = true

          this.station_id = item.id
          await this.getFileList(this.keyword, item.id)


          this.$refs.fileviewTree.setCurrentKey(item.line_id)
          console.log('当时',item.line_id);
          let node = this.getTreeNodeById2(this.treedata[0],item.line_id)
          this.openParent(node)

        }
      })
      this.$store.state.fileViewSearch.stationList = _.cloneDeep(this.$store.state.fileViewSearch.stationList)

   },
    openParent(treeNode){
      if(treeNode.parent_id>0)
      {
        var parent = this.getTreeNodeById2(this.treedata[0],treeNode.parent_id)
        let parent_tode=this.$refs.fileviewTree.getNode(treeNode.parent_id)
        console.log("父节点",parent_tode)
        parent_tode.expand();
        if(parent.parent_id>0)
        {
          this.openParent(parent)
        }
      }
    },
    getTreeNodeById2(tree, id) {
      let data = null
      if (!tree.children) {
        tree.children = []
      }
      if(tree.id==id)
      {
        return  tree;
      }
      for (var i = 0; i < tree.children.length; i++) {
        var item = tree.children[i]
        if (item.id == id) {
          data = item
        }
        if (data) {
          break
        }
        if (item.children) {
          data = this.getTreeNodeById2(item, id)
        }
        if (data) {
          break
        }
      }
      return data
    },
    async getFileList(keyword, station_id) {
      this.$store.state.fileViewSearch.fileTree = {}
      this.listLoading = true
      console.log("关键字",keyword)
      await queryFileTree(keyword,parseInt(station_id)).then(response => {
        console.log("点击后的树",response)
        let newval={
          id:uuid(),
          children:[],
        };
        if (response) {

          response.data.forEach((item)=>{
            if(item.length>0)
            {
              item.forEach((it)=>{

                newval.children.push(it)
              })
            }

          })


          this.mergeChildren(newval)
          console.log("最终的树",newval)
          this.$store.state.fileViewSearch.fileTree = newval
          this.refirsh();
          // this.total = response.data.count
        }
        this.listLoading = false
      })
    },
    mergeChildren(tree,parent) {
      console.log("继承权限",tree,parent)
      if (!tree.children) {
        tree['children'] = []
      }
      if (!tree.filelist) {
        tree['filelist'] = []
      }
      if(!tree.width)
      {
        tree.width=200;
      }
      if(!tree.promise&&parent&&parent.promise)
      {
        console.log("继承权限")
        tree.promise=parent.promise
      }
      tree['newChildren'] = tree.children.concat(tree.filelist)
      tree['selectKey'] = null
      for (var i = 0; i < tree.newChildren.length; i++) {
        this.mergeChildren(tree.newChildren[i],tree)
      }
    },
    refirsh() {
      this.forceKey++
    },
    rightTest(item) {
      console.log(item)
    },
    handleUpload(item) {
      this.$emit('upload', item)
    },
    rightSelectFile(index, key, event) {
      event.preventDefault()
      this.fileTree.selectKey = null
      this.$nextTick(() => {
        this.fileTree.selectKey = key
      })

      const { clientX, clientY } = event
      this.$refs.contextmenu.show({ top: clientY, left: clientX })
    },
    selectFile(index, key) {
      this.fileTree.selectKey = null
      this.$nextTick(() => {
        this.fileTree.selectKey = key
        console.log(this.fileTree, this.fileTree.selectKey, this.fileTree.newChildren[this.fileTree.selectKey])
      })
    },
    resize() {

    }
  }
}
</script>

<style scoped>
.my-resize{
  display: inline-block;position: static;border:none;border-right: 5px solid #dddddd;
}
.my-resize /deep/ .handle-mr{
  border: none;
  background: #eeeeee;
  height: calc(100% + 10px);
  top: 0px;
  width: 5px;
  right: -5px;
  display: block !important;
}
.viewbox{
  width: 100%; height: 60vh;display:flex;overflow-y: scroll;align-items: center;justify-content: center;
}
.viewbox /deep/ canvas{
  position: static !important;
}
.tree-container {
  margin-top: 8px;
}

.tree-container /deep/ .el-tree-node {
  position: relative;
  padding-left: 13px;
}

.tree-container /deep/ .el-tree-node:before {
  width: 1px;
  height: 100%;
  content: '';
  position: absolute;
  top: -38px;
  bottom: 0;
  left: 0;
  right: auto;
  border-width: 1px;
  border-left: 1px solid #b8b9bb;
}

.tree-container /deep/ .el-tree-node:after {
  width: 13px;
  height: 13px;
  content: '';
  position: absolute;
  left: 0;
  right: auto;
  top: 12px;
  bottom: auto;
  border-width: 1px;
  border-top: 1px solid #b8b9bb;
}

.tree-container /deep/ .el-tree > .el-tree-node:before {
  border-left: none;
}

.tree-container /deep/ .el-tree > .el-tree-node:after {
  border-top: none;
}

.tree-container /deep/ .el-tree .el-tree-node:last-child:before {
  height: 50px;
}

.tree-container /deep/ .el-tree .el-tree-node__content {
  color: #000;
  font-size: 14px;
  padding-left: 0 !important;
}

.tree-container /deep/ .el-tree .el-tree-node__children {
  padding-left: 11.5px;
}

.tree-container /deep/ .el-tree .el-tree-node__content > label.el-checkbox {
  margin: 0 5px 0 5px !important;
}

.tree-container /deep/ .el-tree .el-tree-node__expand-icon {
  position: relative;
  z-index: 99;
}

.tree-container /deep/ .el-tree .el-tree-node__expand-icon.is-leaf {
  display: none;
}

.tree-container /deep/ .el-tree .leaf-node-line {
  width: 23px;
  height: 13px;
  content: '';
  position: absolute;
  left: 13px;
  right: auto;
  top: 12px;
  bottom: auto;
  border-width: 1px;
  border-top: 1px solid #b8b9bb;
}

.tree-container /deep/ .el-tree .el-tree-node__content:has(.is-leaf) {

  margin-left: 24px !important;
}

.el-form-item__label {
  padding: 0px !important;
}

.el-drawer__header {
  margin: 0px !important;
  padding: 16px !important;
}

.demo-drawer {
  width: 300px;
}

.file-view-box {
  height: calc(100vh - 126px);
}

.filter-container {
  border-bottom: 1px solid #cccccc;
  padding: 10px 3px 0px 3px;
  overflow: hidden;
  height: 50px;
}

.file-button-box {
  height: 36px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  font-size: 12px;
  cursor: pointer;
  user-select: none;
}

.file-button-box-selected {
  background: #1067de;
  color: #ffffff !important;
}

.gwbox:hover {
  background: #dcdcdc;
}

.file-button-box:hover {
  background: #dcdcdc;
}

.file-button-box-hover {
  background: #dcdcdc;
}

.file-button-img-box {
  width: 36px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.file-button-title {
  display: flex;
  align-items: center;
  flex: 1;
}

.file-button-img-DWI {
  background-position: 0px -1800px;
}
.file-button-img-EPM {
  background-position: 0px -1850px;
}
.file-button-img-SPM {
  background-position: 0px -1900px;
}
.file-button-img {
  width: 16px;
  height: 16px;
  background: url('/static/icons-small.png') no-repeat;
}

.file-button-right {
  font-size: 14px;
  width: 20px;
}

.components-container {
  position: relative;
  height: calc(100vh - 126px);
  margin: 0px;
  border: 2px solid #cccccc;
}

.left-container {
  /*background-color: #F38181;*/
  overflow-y: auto;
  height: 100%;
  padding: 3px;
}

/* 自定义滚动条样式 */
::-webkit-scrollbar {
  width: 8px; /* 宽度 */
}

::-webkit-scrollbar-track {
  background-color: #f1f1f1; /* 轨道颜色 */
}

::-webkit-scrollbar-thumb {
  background-color: #dcdcdc; /* 拇指颜色 */
  border-radius: 5px; /* 圆角 */
}

::-webkit-scrollbar-thumb:hover {
  background-color: #dcdcdc; /* 鼠标悬停时的颜色 */
}

.right-container {
  background-color: #FCE38A;
  height: 200px;
}

.top-container {
  background-color: #FCE38A;
  width: 100%;
  height: 100%;
}

.bottom-container {
  width: 100%;
  background-color: #95E1D3;
  height: 100%;
}
.file-button-img-dir {
  background-position: 0px -50px;
}

.file-button-img-image {
  background-position: 0px -250px;
}

.file-button-img-music {
  background-position: 0px -350px;
}

.file-button-img-vedio {
  background-position: 0px -400px;
}

.file-button-img-txt {
  background-position: 0px -450px;
}

.file-button-img-pdf {
  background-position: 0px -500px;
}

.file-button-img-gw {
  background-position: 0px -550px;
}

.file-button-img-world {
  background-position: 0px -1500px;
}

.file-button-img-exe {
  background-position: 0px -900px;
}

.file-button-img-zip {
  background-position: 0px -1150px;
}

.file-button-img-ppt {
  background-position: 0px -1400px;
}

.file-button-img-excel {
  background-position: 0px -1450px;
}
</style>
